package com.oracle.coherence.patterns.security;

import java.io.InputStream;
import java.util.Properties;

/**
 * For loading System properties from SysProps/file/commandLine.
 *
 * @author Andrew Wilson
 * @version 1.1
 */
public class SystemPropertyLoader {
    public static final String MARKER_ENVIRONMENT = "coherence.incubator.environment";

    public static void addSystemProperties(String resourceName) throws Exception {
        addSystemProperties(resourceName, true);
    }

    public static void addSystemProperties(String resourceName, boolean required) throws Exception {
        InputStream stream = SystemPropertyLoader.class.getResourceAsStream(resourceName);

        if (stream == null) {
            if (required) {
                throw new RuntimeException("Stream is null : " + resourceName);
            }
        } else {
            try {
                Properties properties = new Properties();
                properties.load(stream);
                for (Object key : properties.keySet()) {
                    String value = properties.getProperty((String) key);
                    System.setProperty((String) key, value);
                }
            } finally {
                stream.close();
            }
        }
    }

    public static void loadProperties(String[] args) throws Exception {
        // Load the command line args
        if (args != null) {
            for (int i = 0; i < args.length; i += 2) {
                System.setProperty(args[i], args[i + 1]);
            }
        }

        addSystemProperties("/properties/default.properties", false);
        addSystemProperties("/properties/" + getRequiredProperty(MARKER_ENVIRONMENT) + ".properties");

        // Reload the command line options again to make sure none got wiped.
        if (args != null) {
            for (int i = 0; i < args.length; i += 2) {
                System.setProperty(args[i], args[i + 1]);
            }
        }
    }

    public static String getRequiredProperty(String property) throws Exception {
        String value = System.getProperty(property);
        if (value == null) {
            throw new Exception("Required system property : " + property);
        }
        return value;
    }

    public static void loadEnvironment(String env) throws Exception {
        System.setProperty(MARKER_ENVIRONMENT, env);
        loadProperties(null);
    }

    public static int getRequiredInteger(String property) throws Exception {
        return Integer.parseInt(getRequiredProperty(property));

    }
}
